// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: wsfuyibing <682805@qq.com>
// Date: 2025-04-02

package table

import "fmt"

type (
	// Cell
	// 单元格接口.
	Cell interface {
		GetColspan() int
		GetRowspan() int
		GetWidth() int
		SetColspan(n int) Cell
		SetRowspan(n int) Cell
		String() string
	}

	cell struct {
		colspan, rowspan, width int
		value                   any
	}
)

// NewCell
// 单元格实例.
func NewCell(value any) Cell {
	return (&cell{
		colspan: 1,
		rowspan: 1,
		value:   value,
	}).calc()
}

// +---------------------------------------------------------------------------+
// | Interface methods                                                         |
// +---------------------------------------------------------------------------+

func (o *cell) GetColspan() int       { return o.colspan }
func (o *cell) GetRowspan() int       { return o.rowspan }
func (o *cell) GetWidth() int         { return o.width }
func (o *cell) SetColspan(n int) Cell { o.colspan = n; return o }
func (o *cell) SetRowspan(n int) Cell { o.rowspan = n; return o }

func (o *cell) String() string { return fmt.Sprintf(`%v`, o.value) }

func (o *cell) calc() *cell {
	for _, c := range o.String() {
		if c > 127 {
			o.width += 2
		} else {
			o.width += 1
		}
	}
	return o
}
